<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/9 0009
 * Time: 下午 7:46
 */

namespace app\api\controller;
use app\api\service\Token as TokenService;
use app\common\BaseHelper;
use app\common\model\Ordercommission;
use app\common\model\Salerule;
use app\common\model\User;
use app\common\model\Usercommission;
use app\common\validate\Currency;
use app\lib\exception\ParameterException;
use app\common\validate\MakeMoney;
use app\api\service\Pay as PayService;
use think\Db;

class Sale extends BaseController{
    //分销状态，0=可退换货，1=不可退货，2=已抽取拥金'
    const SALE_STATUS_0 = 0;
    const SALE_STATUS_1 = 1;
    const SALE_STATUS_2 = 2;

    protected $beforeActionList = [
        'checkExclusiveScope' => ['only' => 'MakeMoney']
    ];

    //获取成功邀请的下级
    public function getSubordinateList(){
        $uid = TokenService::getCurrentUid();
        //$uid = "ecc3763c184b035d37884a";
        $userModel = new User();
        $user = $userModel->field('id,avatarUrl,nickName,mobile')->where('chiefUserId',$uid)->where('status',1)->select();
        if($user){
            return show(config('status.SUCCESS_STATUS'),'ok',$user);
        }else{
            return show(config('status.SUCCESS_STATUS'),'没有下级用户','');
        }
    }

    //获取预计收益
    public function GetExpectedEarnings()
    {
        $uid = TokenService::getCurrentUid();
        //$uid = "ecc3763c184b035d37884a";
        $ordercommission = new Ordercommission();
        $time = time() - config('order.order_refund') * 24 * 60 * 60;
        $where = [
            'shangjiId' => ['=', $uid],
            'status' => self::SALE_STATUS_0,
            //'create_time' => ['<', $time]
        ];
        $shouyi = $ordercommission->where($where)->select();
        if($shouyi){
            $yujimoney = 0;
            foreach ($shouyi as &$v){
                $user = User::get($v['userId']);
                if($user){
                    $v['nickName'] = $user->nickName;
                    $v['avatarUrl'] = $user->avatarUrl;
                }else{
                    $v['nickName'] = '';
                    $v['avatarUrl'] = '';
                }
                $yujimoney += ($v->total*$v->proportion) / 100;
            }
            $data = [
                'yujimoney' => number_format($yujimoney / 100, 2),
                'data' => $shouyi
            ];
            return show(config('status.SUCCESS_STATUS'), 'ok', $data);
        }else{
            return show(config('status.SUCCESS_STATUS'), '没有预计收益', '');
        }

    }
    //获取实际收益
    public function GETRealIncome(){
        $ordercommission = new Ordercommission();
        $shouyi = $ordercommission->where(function ($query){
            $uid = TokenService::getCurrentUid();
            // $uid = "29080696e9d4e314efdba0";
            $query->where('shangjiId',$uid)->where('status',['=',self::SALE_STATUS_1],['=',self::SALE_STATUS_2],'OR');
        })->select();
        if($shouyi){
            $shijimoney = 0;
            foreach ($shouyi as &$v){
                $user = User::get($v['userId']);
                if($user){
                    $v['nickName'] = $user->nickName;
                    $v['avatarUrl'] = $user->avatarUrl;
                }else{
                    $v['nickName'] = '';
                    $v['avatarUrl'] = '';
                }
                $shijimoney += ($v->total*$v->proportion) / 100;
            }
            $data = [
                'shijimoney' => number_format($shijimoney / 100, 2),
                'data' => $shouyi
            ];
            return show(config('status.SUCCESS_STATUS'), 'ok',$data);
        }else{
            return show(config('status.SUCCESS_STATUS'), '没有实际收益', '');
        }
    }

    //佣金提现列表
    public function getPutforwardList(){
        $uid = \app\api\service\Token::getCurrentUid();
        $Usercommission = Usercommission::where('userId',$uid)->where('status',['=',1],['=',2],'OR')->select();
        if($Usercommission){
            return show(config('status.SUCCESS_STATUS'),'ok',$Usercommission);
        }else{
            return show(config('status.SUCCESS_STATUS'),'没有提现记录','没有提现记录');
        }
    }

    //提现申请
    public function PutforwardApply(){
        $uid = TokenService::getCurrentUid();
        $tenantid = TokenService::getTenantid();
        (new Currency())->goCheck();
        $amount = input('post.amount',0,'trim');
        $user = User::where(['id'=>$uid,'status'=>1])->find();
        if($amount*100<=$user->totalIncome){
            $usercom = new Usercommission();
            $usercom->id = BaseHelper::getUUID();
            $usercom->userId = $uid;
            $usercom->amount = $amount*100;
            $usercom->accountName = '微信零钱';
            $usercom->tenantId = $tenantid;
            $usercom->type = 1;
            $usercom->status = 1;
            $usercom->merchantOrderNo = \app\api\service\Order::makeOrderNo();
            if($usercom->save()){
                return show(config('status.SUCCESS_STATUS'),'创建提现申请订单成功',$usercom);
            }else{
                throw new ParameterException([
                    'msg' => '提现申请失败，内部原因'
                ]);
            }

        }else{
            return show(config('status.ERROR_STATUS'),'提现金额超过余额','提现金额超过余额');
        }

    }

    //商户向申请提现用户的微信零钱打款
    public function MakeMoney($id = ''){
        (new MakeMoney())->goCheck();
        $dpay = new PayService($id);
        return $dpay->shanghuPay();


    }



    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 分销规则
     */
    public function getSaleRule()
    {
        $param = self::getHttpParam();
        if (empty($param->tenantId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'tenantId不能这空');
        } else {
            $tenantId = $param->tenantId;
            $saleRule = Salerule::where('tenantId', $tenantId)->find();
            if (empty($saleRule)) {
                return show(config('status.EMPTY_STATUS'), self::NOT_DATA, '未查到分销规则');
            } else {
                return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $saleRule);
            }
        }
    }
}